package com.bl.student.dao.redis;

import com.bl.student.dao.redis.model.AdminInfo;
import com.google.common.base.Optional;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

/**
 * Created by yujingyi on 2017/6/17.
 */
@Component
@Log4j2
public class AdminInfoDao extends AbstractDao{

    private final String ADMIN_AUTH_KEY_PREFIX = "ADMIN_AUTH_";

    private final long ADMIN_COOKIE_EXPIRE = 1000 * 60 * 60 * 24 * 7;

    public Optional<AdminInfo> getAdminInfoByAuthCookie(String authCookie) {
        RedissonClient redisson = getRedisson();

        AdminInfo authInfo = hgetAll(genKey(ADMIN_AUTH_KEY_PREFIX, authCookie), AdminInfo.class);

        return authInfo == null ?
                Optional.<AdminInfo>absent() :
                Optional.fromNullable(authInfo);
    }

    public void setAdminInfo(String authCookie, AdminInfo authInfo) {

        hsetAll(genKey(ADMIN_AUTH_KEY_PREFIX, authCookie), authInfo);
        pexpire(genKey(ADMIN_AUTH_KEY_PREFIX, authCookie), ADMIN_COOKIE_EXPIRE);

    }

    public boolean delAdminInfo(String authCookie) {

        return del(genKey(ADMIN_AUTH_KEY_PREFIX, authCookie)) > 0 ? true : false;
    }
}
